package com.samphanie.security.security.authorization;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.samphanie.common.constants.SystemConstants;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * 判断用户是否有访问权限
 * @Author ZSY
 * @createTime 2021/8/31 13:37
 */
@Component
public class AuthorizationDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        // 当接口未被配置资源时直接放行
        if (CollUtil.isEmpty(collection)) {
            return;
        }

        for (ConfigAttribute configAttribute : collection) {
            // 将访问所需资源或用户拥有资源进行比对
            String needAuthority = configAttribute.getAttribute();
            String authorityPrefix = StrUtil.removePrefix(needAuthority, "[");
            String authoritySuffix = StrUtil.removeSuffix(authorityPrefix, "]");
            List<String> authorities = StrUtil.splitTrim(authoritySuffix, ",");
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if (SystemConstants.ROOT_ROLE_CODE.equals(authority.getAuthority())) { // 如果是超级管理员则放行
                    return;
                }
                for (String auth : authorities) {
                    if (auth.trim().equals(authority.getAuthority())) {
                        return;
                    }
                }
//                if (needAuthority.trim().equals(authority.getAuthority())) {
//                    return;
//                }
            }
        }

        throw new AccessDeniedException("抱歉，您没有访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
